package com.china_goldcard.utils;

import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;

/**
 * 计时器
 */

public class CountTimerUtils extends CountDownTimer {

    public interface CountTimerListener{

        void timerCountRunning(long remainSecond);

        void timerFinished();
    }

    private Handler mHandler;
    private CountTimerListener listener;
    public static final int          IN_RUNNING  = 1001;
    public static int                END_RUNNING = 1002;

    public CountTimerUtils(long totalSecond, long intervalSecond, CountTimerListener listener) {
        super(totalSecond * 1000, intervalSecond * 1000);
        this.listener = listener;
    }

    public CountTimerUtils(long totalSecond, long intervalSecond){
        this(totalSecond,intervalSecond,null);
    }

    /**
     * 获取handler
     * @return
     */
    private Handler getHandler(){

        return new Handler () {

            @Override
            public void handleMessage(Message msg){
                super.handleMessage (msg);
                if (msg.what == CountTimerUtils.IN_RUNNING) {
                    // 正在倒计时
                    if (listener != null) {
                        long remainSecond = (Long) msg.obj;
                        listener.timerCountRunning (remainSecond);
                    }
                } else if (msg.what == CountTimerUtils.END_RUNNING) {
                    // 完成倒计时
                    if (listener != null) {
                        listener.timerFinished ();
                    }
                }
            }
        };
    }


    @Override
    public void onTick(long millisUntilFinished){
        if (mHandler != null) {
            Message msg = mHandler.obtainMessage ();
            msg.what = IN_RUNNING;
            msg.obj = millisUntilFinished / 1000;
            mHandler.sendMessage (msg);
        }
    }

    @Override
    public void onFinish(){
        if (mHandler != null) {
            Message msg = mHandler.obtainMessage ();
            msg.what = END_RUNNING;
            mHandler.sendMessage (msg);
        }
    }

    public void setListener(CountTimerListener listener) {
        this.listener = listener;
    }
}
